package com.feizhi.inventory.fragment.exportdetails;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.viewpager2.widget.ViewPager2;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.bean.InventoryDetailsBean;
import com.feizhi.inventory.database.Task;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.databinding.FragmentExportDetailsBinding;
import com.feizhi.inventory.fragment.Inventorydetails.ViewPagerAdapter;
import com.feizhi.inventory.fragment.exportdetails.exportalready.ExportAlreadyFragment;
import com.feizhi.inventory.fragment.exportdetails.exportloss.ExportLossFragment;
import com.feizhi.inventory.fragment.exportdetails.exportprofit.ExportProfitFragment;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *  数据导出
 * */
public class ExportDetailsFragment extends Fragment implements View.OnClickListener {


    private static final int PERMISSION_REQUEST_EXTERNAL_STORAGE = 100;

    private FragmentExportDetailsBinding mBinding;

    private ExportDetailsAdapter adapter;
    private ImageView imageBack;
    private MainActivity mActivity;
    private List<InventoryDetailsBean> data;
    private TextView titleText;
    private TextView titleTtextBack;
    private ViewPagerAdapter viewPagerAdapter;
    private List<Fragment> list;

    private List<TaskDetails> taskDetailsList;
    private String tid;
    private TaskDetailsDao taskDetailsDao;
    private TaskDao taskDao;
    private int count;
    private String tableName;
    private String detailsDataName;
    private List<Task> data1;

    public ExportDetailsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivity = (MainActivity) getActivity();
        getPermission();
    }

    private void getPermission() {
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，请求权限
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_EXTERNAL_STORAGE);
        } else {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mBinding = FragmentExportDetailsBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        //处理事件
        setOnClickListener();
    }

    private void setOnClickListener() {


        titleTtextBack.setOnClickListener(this);
        imageBack.setOnClickListener(this);


        //已盘点
        mBinding.counted.setOnClickListener(this);
        //盘盈
        mBinding.inventoryProfit.setOnClickListener(this);
        //
        mBinding.inventoryLoss.setOnClickListener(this);

        mBinding.viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                switch (position) {
                    case 0:
                        extracted();
                        break;
                    case 1:
                        extracted();
                        break;
                    case 2:
                        extracted();
                        break;
                    default:break;
                }
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        // 当前页面为第一页(已盘点)
                        mBinding.counted.setBackgroundResource(R.drawable.white);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                        break;
                    case 1:
                         //当前页面为第二页(盘盈)
                        mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.white);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                        break;
                    case 2:
                         //当前页面为第三页(盘亏)
                        mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                        mBinding.inventoryLoss.setBackgroundResource(R.drawable.white);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager2.SCROLL_STATE_IDLE: // 静止状态
                        // do something
                        break;
                    case ViewPager2.SCROLL_STATE_DRAGGING: // 拖拽中
                        mBinding.viewPager2.setUserInputEnabled(false); // 禁止用户滑动切换页面
                        // do something
                        break;
                    case ViewPager2.SCROLL_STATE_SETTLING: // 自动滚动中
                        // do something
                        break;
                }
            }
        });

        mBinding.readRfid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                exportDataToExcelPlus();
            }
        });

    }

    private void extracted() {
        LiveEventBus.get().with("tid").post(tid);
    }

    //初始化控件
    private void initView() {
        DaoSession daoSession = ((dbApp) mActivity.getApplication()).getDaoSession();
        taskDetailsDao = daoSession.getTaskDetailsDao();
        taskDao = daoSession.getTaskDao();



        Bundle bundle = getArguments();
        if (bundle != null) {
            tid = bundle.getString("tid");
            detailsDataName = bundle.getString("sheetDataName");

        }
       count = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid), TaskDetailsDao.Properties.State.eq("已盘点")).list().size();

        int countprofit = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid),TaskDetailsDao.Properties.State.eq("盘盈")).count();

        //盘盈的数量
        mBinding.textInventoryProfit.setText("" + countprofit);

        mBinding.textCounted.setText("" + count);
        mBinding.inventoryNumber.setText(tid);

        int countLoss = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid),TaskDetailsDao.Properties.State.eq("盘亏")).count();
        mBinding.textInventoryLoss.setText("" + countLoss);

        int noCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid),TaskDetailsDao.Properties.State.eq("未盘点")).count();
        int yiCount = (int) taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid),TaskDetailsDao.Properties.State.eq("已盘点")).count();
        int profitCount = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(tid),TaskDetailsDao.Properties.State.eq("盘亏")).list().size();

        //接收上个页面传过来的盘点总数
        mBinding.inventoryCount.setText("" + (noCount + yiCount + profitCount));


        imageBack = mActivity.findViewById(R.id.title_back);
        titleText = mActivity.findViewById(R.id.title_text);
        titleTtextBack = mActivity.findViewById(R.id.title_text_back);
        titleTtextBack.setVisibility(View.VISIBLE);

        titleText.setText("数据导出");
        imageBack.setVisibility(View.VISIBLE);

        //添加Fragment页面，设置ViewPager2的适配器
        list = new ArrayList<>();
        list.add(new ExportAlreadyFragment());
        list.add(new ExportProfitFragment());
        list.add(new ExportLossFragment());
        viewPagerAdapter = new ViewPagerAdapter(mActivity.getSupportFragmentManager(), getLifecycle(), list);
        mBinding.viewPager2.setAdapter(viewPagerAdapter);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                backFragment();
                break;
            case R.id.title_text_back:
                backFragment();
                break;
            case R.id.counted:
                mBinding.counted.setBackgroundResource(R.drawable.white);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.viewPager2.setCurrentItem(0, false);

                break;
            case R.id.inventory_profit:
                mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.white);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.viewPager2.setCurrentItem(1, false);
                break;
            case R.id.inventory_loss:
                mBinding.counted.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryProfit.setBackgroundResource(R.drawable.details_item_bg);
                mBinding.inventoryLoss.setBackgroundResource(R.drawable.white);
                mBinding.viewPager2.setCurrentItem(2, false);
                break;
            default:break;
        }
    }

    //返回上一层Fragment
    private void backFragment() {
        Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
    }

    public void exportDataToExcelPlus() {
        ProgressDialog progressDialog = new ProgressDialog(mActivity);
        progressDialog.setTitle("导出数据");
        progressDialog.setMessage("正在导出ing...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                    Sheet sheet = workbook.createSheet("物品清单");

                    taskDetailsList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.like(tid)).list();
                    List<TaskDetails> rfid = new ArrayList<>();
                    rfid.addAll(taskDetailsList);




                    //创建表头
                    createHeaderRow(sheet);

                    for (int i = 0; i < rfid.size(); i++) {
                        createDataRow(sheet, rfid.get(i), i + 1);
                    }

                    // 导出 xlsx 文件
                    File file = new File(Environment.getExternalStorageDirectory(), rfid.get(0).getTaskID() + "(导出)" + ".xlsx");
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        workbook.write(fos);
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(mActivity, "导出成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(mActivity, "导出失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void createHeaderRow(Sheet sheet) {
        Row headerRow = sheet.createRow(0);
        String[] headers = {"物品编码", "物资名称",
                "使用单位", "规格",
                "类型", "保管人",
                "入库时间", "存放地点",
                "打印编码", "备注",
                "备注2", "备注3", "状态"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
    }

    private void createDataRow(Sheet sheet, TaskDetails details, int rowNum) {
        Row dataRow = sheet.createRow(rowNum);
        dataRow.createCell(0).setCellValue(details.getId());
        dataRow.createCell(1).setCellValue(details.getName());
        dataRow.createCell(2).setCellValue(details.getDepartment());
        dataRow.createCell(3).setCellValue(details.getSpec());
        dataRow.createCell(4).setCellValue(details.getType());
        dataRow.createCell(5).setCellValue(details.getCustodian());
        dataRow.createCell(6).setCellValue(details.getInputDate());
        dataRow.createCell(7).setCellValue(details.getSavePlace());
        dataRow.createCell(8).setCellValue(details.getEpcID());
        dataRow.createCell(9).setCellValue(details.getNotes_1());
        dataRow.createCell(10).setCellValue(details.getNotes_2());
        dataRow.createCell(11).setCellValue(details.getNotes_3());
        dataRow.createCell(12).setCellValue(details.getState());
    }

}